const BaseIpcHandler = require('../BaseIpcHandler');
const { DatasetListDB } = require('../../dbs/dbDatasetList');

class UpdateSubsetHandler extends BaseIpcHandler {
    async handle(event, params) {
        // 解析参数
        // console.log('>> UpdateSubsetHandler params = ', params);
        const { id, dataset_id, image_dir, label_dir } = params;

        // 业务逻辑
        let result = null;
        try {
            // 判断dataset_id是否存在
            let isValidID = await this.app.db.datasets.hasDataset(dataset_id);
            if (!isValidID) {
                throw { errorCode: -2, message: `Dataset ID ${dataset_id} does not exist!` };
            }

            // 打开详情数据库，获取对应的subsets信息
            let dblist = this.app.list_dbs[dataset_id];
            if (!dblist) {
                this.app.list_dbs[dataset_id] = new DatasetListDB(this.app, dataset_id);
                dblist = this.app.list_dbs[dataset_id];
            }

            // 构建更新数据
            let subsetInfo = {
                id,
                image_dir,
                label_dir
            };
            result = await dblist.subsets.update(subsetInfo);
        } catch (err) {
            console.error(`Update Subset Failed!, Error = `, err);
            result = { code: -1, msg: err.message };
        }

        // 返回结果
        if (event.from === 'localserver') {
            event.resp.send(result);
        } else {
            return result;
        }
    }
}

module.exports = UpdateSubsetHandler;
